package com.wswy.wzcx.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;

import com.che.libcommon.api.ApiOptionalResultObserver;
import com.che.libcommon.api.BaseResult;
import com.che.libcommon.utils.ToastUtils;
import com.wswy.wzcx.R;
import com.wswy.wzcx.api.Api;
import com.wswy.wzcx.model.DataCenter;
import com.wswy.wzcx.model.UserMode;

/**
 * Created by wangduheng26 on 2018/1/22.
 * wangduheng26@gmail.com
 */

public class SetupPwdFragment extends PwdFragment {
    public static final String TAG = "SetupPwdFragment";
    public static final String ARGS_CODE = "arg.code";
    public static final String ARGS_PHONE_KEY = "args.phone_key";
    private String code,phone;

    public static SetupPwdFragment newInstance(String phone,String code) {

        Bundle args = new Bundle();
        args.putString(ARGS_CODE, code);
        args.putString(ARGS_PHONE_KEY,phone);
        SetupPwdFragment fragment = new SetupPwdFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Bundle bundle = getArguments();
        if (bundle != null && bundle.containsKey(ARGS_CODE) ) {
            code = bundle.getString(ARGS_CODE);
            phone = bundle.getString(ARGS_PHONE_KEY);
        }
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        editText.setHint("请输入新密码");
        tvTitle.setText("密码");
    }
    @Override
    protected void submit() {
        final Editable text = editText.getText();
        if (TextUtils.isEmpty(code)) {
            showToast("验证码为空");
            return;
        }
        if (!TextUtils.isEmpty(text)) {
            Api.get().submitNewPwd(phone,code,String.valueOf(text))
                    .subscribe(new ApiOptionalResultObserver<UserMode>() {
                        @Override
                        protected void onApiResult(@Nullable UserMode userMode) {
                            if(userMode!=null){
                              DataCenter.get().updateUserMode(userMode);
                                showSuccessDialog();
                            }else{
                                ToastUtils.showText(R.string.unknown_exption);
                            }
                        }

                        @Override
                        protected void onApiError(@Nullable BaseResult result) {
                            toastErrorMsg(result);
                        }
                    });
        } else {
            showToast("密码不能为空");
        }
    }


    @Override
    public String getFragmentTitle() {
        return "设定密码";
    }
}
